<template>
    <div id="map"></div>
    <div class="controls">
        <button id="start" @click="startMoving">开始移动</button>
        <button id="stop" @click="stopMoving">停止移动</button>
        <div>
            速度(km/h):
            <input type="range" id="speed" min="1" max="120" value="30" @input="onInput" />
        </div>
        <div>
            平滑系数:
            <input type="range" id="smoothness" min="1" max="100" value="20" @input="smoothness" />
        </div>
    </div>
</template>
<script lang="ts" setup>
import TileLayer from 'ol/layer/Tile';
import { XYZ } from 'ol/source';
import { TDMAP_TK } from '@/utils/constant';
import MapType from 'ol/Map.js';
import { Feature, View } from 'ol';
import { fromLonLat } from 'ol/proj';
import VectorSource from 'ol/source/Vector';
import VectorLayer from 'ol/layer/Vector';
import { LineString, Point } from 'ol/geom';
import Style from 'ol/style/Style';
import Stroke from 'ol/style/Stroke';
import Icon from 'ol/style/Icon';
import { Coordinate } from 'ol/coordinate';
// 天地图矢量图层
const tdMapVectorLayer = new TileLayer({
    zIndex: 30,
    className: 'tdVector',
    visible: true,
    source: new XYZ({
        url: `https://t0.tianditu.gov.cn/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=${TDMAP_TK}`,
        wrapX: false
    })
});
// 天地图标注层
const tdMapCvaLayer = new TileLayer({
    zIndex: 31,
    className: 'tdCva',
    visible: true,
    source: new XYZ({
        url: `https://t0.tianditu.gov.cn/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=${TDMAP_TK}`,
        wrapX: false
    })
});
let map: MapType;
let carFeature: any;
// 2. 创建测试路线
const routeCoords:Coordinate[] = [
[116.478935, 39.997761],
    [116.478939, 39.997825],
    [116.478912, 39.998549],
    [116.478912, 39.998549],
    [116.478998, 39.998555],
    [116.478998, 39.998555],
    [116.479282, 39.99856],
    [116.479658, 39.998528],
    [116.480151, 39.998453],
    [116.480784, 39.998302],
    [116.480784, 39.998302],
    [116.481149, 39.998184],
    [116.481573, 39.997997],
    [116.481863, 39.997846],
    [116.482072, 39.997718],
    [116.482362, 39.997718],
    [116.483633, 39.998935],
    [116.48367, 39.998968],
    [116.484648, 39.999861]
].map(coord => fromLonLat(coord));

// 5. 使用车头向上的PNG图片（示例URL，请替换为实际URL）
const carIconUrl = new URL('@/assets/img/car.png', import.meta.url).href;

// 6. 生成超密集路径点（每段50个点）
function createDensePath(coords:Coordinate[], segmentsPerSection: number):Coordinate[] {
    const densePath:Array<[number,number]> = [];
    for (let i = 0; i < coords.length - 1; i++) {
        const start = coords[i];
        const end = coords[i + 1];

        for (let j = 0; j <= segmentsPerSection; j++) {
            const ratio = j / segmentsPerSection;
            densePath.push([
                start[0] + (end[0] - start[0]) * ratio,
                start[1] + (end[1] - start[1]) * ratio
            ]);
        }
    }
    return densePath;
}

const denseRoute:Coordinate[] = createDensePath(routeCoords, 50);

// 7. 小车移动控制
let animationId = 0;
let currentIndex = 0;
let speed = 30;
let lastTimestamp = 0;
let lastAngle = 0;
let smoothFactor = 0.2; // 默认平滑系数

// 针对车头向上PNG的角度计算（带平滑）
function calculateSmoothedAngle(currentPoint: Coordinate, nextPoint: Coordinate) {
    const dx = nextPoint[0] - currentPoint[0];
    const dy = nextPoint[1] - currentPoint[1];

    // 计算原始角度（正东为0，逆时针增加）
    let newAngle = Math.atan2(dy, dx);

    // 调整为车头向上的角度（减去π/2）
    newAngle = newAngle - Math.PI / 2;

    // 角度平滑处理（避免360度跳变）
    const angleDiff = ((newAngle - lastAngle + Math.PI) % (2 * Math.PI)) - Math.PI;
    const smoothedAngle = lastAngle + angleDiff * smoothFactor;

    lastAngle = smoothedAngle;
    return smoothedAngle;
}

function updateCarStyle(position: Coordinate, nextPosition: Coordinate) {
    const angle = calculateSmoothedAngle(position, nextPosition);

    carFeature.setStyle(
        new Style({
            image: new Icon({
                src: carIconUrl,
                scale: 1,
                rotation: angle,
                anchor: [0.5, 0.5],
                rotateWithView: true
            })
        })
    );
}

function moveAlong(timestamp: number) {
    if (!lastTimestamp) lastTimestamp = timestamp;
    const elapsed = timestamp - lastTimestamp;
    lastTimestamp = timestamp;

    // 计算移动步长（基于速度）
    const step = (speed * elapsed) / 1000;

    // 更新位置
    currentIndex = Math.min(currentIndex + step, denseRoute.length - 1);

    // 获取当前和下一个位置点
    const currentIdx = Math.floor(currentIndex);
    const nextIdx = Math.min(currentIdx + 1, denseRoute.length - 1);

    const currentPoint = denseRoute[currentIdx];
    const nextPoint = denseRoute[nextIdx];

    // 计算插值位置
    const fraction = currentIndex - currentIdx;
    const interpolatedPoint = [
        currentPoint[0] + (nextPoint[0] - currentPoint[0]) * fraction,
        currentPoint[1] + (nextPoint[1] - currentPoint[1]) * fraction
    ];

    // 更新小车
    carFeature.getGeometry().setCoordinates(interpolatedPoint);
    updateCarStyle(interpolatedPoint, nextPoint);

    // 保持地图中心跟随小车
    map.getView().setCenter(interpolatedPoint);

    // 检查是否到达终点
    if (currentIndex >= denseRoute.length - 1) {
        stopMoving();
        return;
    }

    animationId = requestAnimationFrame(moveAlong);
}

function startMoving() {
    if (!animationId) {
        if (currentIndex >= denseRoute.length - 1) {
            currentIndex = 0;
            lastAngle = 0;
        }
        lastTimestamp = 0;
        animationId = requestAnimationFrame(moveAlong);
    }
}

function stopMoving() {
    if (animationId) {
        cancelAnimationFrame(animationId);
        animationId = 0;
    }
}
const smoothness = (e: any) => {
    smoothFactor = 0.01 + (parseInt(e.target.value) / 100) * 0.49;
};



const initMap = () => {
    // 1. 初始化地图
    map = new MapType({
        target: 'map',
        layers: [tdMapVectorLayer, tdMapCvaLayer],
        view: new View({
            center: fromLonLat([116.478935, 39.997761]),
            zoom: 17
        })
    });
    // 3. 创建路线图层
    const routeLayer = new VectorLayer({
        source: new VectorSource({
            features: [
                new Feature({
                    geometry: new LineString(routeCoords)
                })
            ]
        }),
        style: new Style({
            stroke: new Stroke({
                color: '#4285F4',
                width: 6
            })
        }),
        zIndex:33
    });
    map.addLayer(routeLayer);

    // 4. 创建小车（使用车头向上的PNG图片）
    carFeature = new Feature({
        geometry: new Point(routeCoords[0])
    });
    carFeature.setStyle(
        new Style({
            image: new Icon({
                src: carIconUrl,
                scale: 1,
                rotation: 0,
                anchor: [0.5, 0.5],
                rotateWithView: true
            })
        })
    );
    const carLayer = new VectorLayer({
        source: new VectorSource({
            features: [carFeature]
        }),
        zIndex:33
    });
    map.addLayer(carLayer);
};
const onInput = (e: any) => {
    speed = parseInt(e.target.value);
};
onMounted(() => {
    initMap();

    // 9. 初始设置
    updateCarStyle(denseRoute[0], denseRoute[1]);
});
</script>
<style lang="scss" scoped>
#map {
    width: 100%;
    height: 100vh;
}
.controls {
    position: absolute;
    top: 10px;
    left: 10px;
    z-index: 1000;
    background: rgba(255, 255, 255, 0.8);
    padding: 10px;
    border-radius: 5px;
}
</style>
